<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/19
 * Time: 11:06
 */
namespace app\admin\controller;

use app\admin\model\FinanceModel;
use app\admin\model\OrderModel;
use app\admin\model\MemberModel;
use think\Db;
use think\Request;

class Finance extends Base
{
	/**
     * 财务管理
     * 黄
     * 18-04-19
     */
    public function index ()
    {

    }
    //订单录入
    public function orderInput ()
    {
		//支付方式
        $payTypeArr = Db::name('member_attr')->where(['pid'=>10])->select();
		$this->assign([
			'payTypeArr' => $payTypeArr
		]);
        return $this->fetch();
    }
	/**
	 * 读取客户
	 */
	 public function memList()
	 {
		 if (request()->isAjax()) {
             $param = input('param.');
             $limit = $param['pageSize'];
             $offset = ($param['pageNumber'] - 1) * $limit;
             $where = [];
             if (!empty($param['name'])) {
                 $where['name'] = ['like', '%' . $param['name'] . '%'];
             }
             if (!empty($param['phone'])) {
                 $where['phone'] = ['like', '%' . $param['phone'] . '%'];
             }
			 $where['status'] = ['neq',8];
             $member = new MemberModel();
             $selectResult = $member->getMemberByWhere($where, $offset, $limit);
             $return['total'] = $member->getAllMember($where);  // 总数据
             $return['rows'] = $selectResult;
             return json($return);
         }
         return $this->fetch();
	 }
    /**
	 *订单列表
	 */
    public function businOrder ()
    {
        if (request()->isAjax()) {
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [];
			if(!empty($param['stu_name'])){
				$where['stu_name'] = ['like', '%' . $param['stu_name'] . '%'];;
			}
			if(!empty($param['order_sn'])){
				$where['order_sn'] = ['like', '%' . $param['order_sn'] . '%'];;
			}
			$where['delete_status'] = array('neq',1);
            $order = new OrderModel();
            $selectResult = $order->orderList($where, $offset, $limit);
            foreach($selectResult as &$vo){
                $vo['gradeN'] = Db::name('product_attr')->where(['id'=>$vo['grade']])->value('name');//层次
                $vo['systemN'] = Db::name('product_attr')->where(['id'=>$vo['system']])->value('name');//学制
                $vo['acquisition_modeN'] = Db::name('product_attr')->where(['id'=>$vo['acquisition_mode']])->value('name');//授课模式
                $vo['payment_methodN'] = Db::name('product_attr')->where(['id'=>$vo['payment_method']])->value('name');//缴费方式
                switch ($vo['pay_type']){
                    case 1:
                        $vo['pay_typeN'] = '现金';
                        break;
                    case 2:
                        $vo['pay_typeN'] = '刷卡';
                        break;
                    case 3:
                        $vo['pay_typeN'] = '支付宝';
                        break;
                    case 4:
                        $vo['pay_typeN'] = '微信';
                        break;
                    default:
                        $vo['pay_typeN'] = '其他';
                }
                switch ($vo['status']){
                    case 0:
                        $vo['statusN'] = '已取消';
                        break;
                    case 1:
                        $vo['statusN'] = '进行中';
						$vo['operate'] = '<a href="javascript:deleteOre('.$vo['id'].')" class="btn btn-success btn-sm">发起退款</a>';//添加按钮
                        break;
                    case 2:
                        $vo['statusN'] = '已完成';
                        break;
                    case 3:
                        $vo['statusN'] = '退款';
                        break;
					default:
						$vo['statusN'] = '退款中';
                }
//				$vo['operate'] = '<a href="javascript:void(0)" class="btn btn-success btn-sm">发起退款</a>';//添加按钮
            }

            $return['total'] = $order->getAllOrder($where);  // 总数据
            $return['rows'] = $selectResult;
            return json($return);
        }
        return $this->fetch();
    }
    /**
	 * 发起退款
	 */
    public function Gathering ()
    {
		$param = input('param.');
		if ($param['deleteNum'] < 0){
			return msg(-1, '', '金额输入错误');
		}
        $order = new OrderModel();
        $gather_status = $order->getGathering($param);
        return $gather_status;
    }
    
	/**
	 * 删除订单
	 * @param $id
	 * @return status
	 */
	public function deleteOrder ()
	{
		$param = $_POST['param'];
		$member = new OrderModel();
		$returnMsg = $member->delOrder($param);
		return $returnMsg;
	}
    /**
     * 拼装操作按钮
     * @param $id 跟踪记录
     * @return array
     */
    private function makeButton1($id)
    {
        return [
            '发起退款' => [
//                'auth' => 'finance/gathering',
//                'href' => url('finance/gathering', ['id' => $id]),
                'auth' => 'member/memberedit',
                'href' => url('member/memberedit', ['id' => $id]),
                'btnStyle' => 'success',
                'icon' => 'fa fa-paste',
            ]
        ];
    }

/*黄*/
#-----------------------------------------------------------------------------------------------#
/**
 * [财务流水列表]
 */
public function accList (){
	$FincModel = new FinanceModel();
	if(request()->isAjax()){
		$param = input('param.');
		$limit = $param['pageSize'];
		$offset = ($param['pageNumber'] - 1) * $limit;
		$where = ['delete_status' => 0];
		$sortName = input('sortName');
		$sortOrder = input('sortOrder');
		$orderBy = $sortName." ".$sortOrder;
		$this->WhereSn($param['seaSn'],$FincModel);
		$this->WhereName($param['seaName'],$FincModel);
		$this->WhereSource($param['seaSource'],$FincModel);
		$this->WhereStatus($param['seaStatus'],$FincModel);
		$this->WhereTime($param['seaTime'],$FincModel);
		$return['rows'] = $FincModel->getInfoByWhere($where,true,$offset,$limit,$orderBy);
		$this->WhereSn($param['seaSn'],$FincModel);
		$this->WhereName($param['seaName'],$FincModel);
		$this->WhereSource($param['seaSource'],$FincModel);
		$this->WhereStatus($param['seaStatus'],$FincModel);
		$this->WhereTime($param['seaTime'],$FincModel);
		$return['total'] = $FincModel->getInfoByWhere($where);
		$return['rows'] = $this->translateFince($return['rows']);
		$return['sum'] = 0;
		foreach($return['rows'] as $k => $v){
			$return['sum'] += $v['total_amount'];
		}
		return $return;
	}
	return $this->fetch();
}
public function WhereSn($param,$FincModel){
	$FincModel->where(function($query)use($param){
		if($param){
			$query->whereOr(['order_sn'=>["like","%".$param."%"]]);
			$query->whereOr(['account_sn'=>["like","%".$param."%"]]);
		}
	});
}
public function WhereName($param,$FincModel){
	$st = DB::name('member')->where('name','like',"%".$param."%")->field('id')->select();
	$staff = DB::name('user')->where('real_name','like',"%".$param."%")->field('id')->select();
	foreach($staff as $v){
		array_push($st,$v);
	}
	$st = array_merge(array_filter($st));
	if(empty($st)){
		$FincModel->where('s_id',-999);
	}else{
		$FincModel->where(function($query)use($st){
			foreach($st as $k => $v){
				$query->whereOr('s_id',$v['id']);
				$query->whereOr('m_id',$v['id']);
			}
		});
	}
}
public function WhereSource($param,$FincModel){
	if($param != ''){
		$FincModel->where('source',$param);
	}
}
public function WhereStatus($param,$FincModel){
	if($param != ''){
		$FincModel->where('status',$param);
	}
}
public function WhereTime($param,$FincModel){
	if($param != ''){
		$start_time = strtotime(explode(" - ",$param)[0]);
		$end_time = strtotime(explode(" - ",$param)[1]);
		$FincModel->whereTime('finish_time','between',[$start_time,$end_time]);
	}
}
public function WhereTimeReport($param,$FincModel){
	if($param != ''){
		$start_time = strtotime(explode(" - ",$param)[0]." 00:00:00");
		$end_time = strtotime(explode(" - ",$param)[1]." 23:59:59");
		$FincModel->whereTime('receivables_time','between',[$start_time,$end_time]);
	}
}

/**
 * [财务流水信息补充]
 */
public function translateFince($param){
	foreach($param as $k => $v){
		if($v['status'] == 0){
			$param[$k]['status_name'] = "<span class='span-danger'>未支付</span>";
		}elseif($v['status'] == 1 && $v['source'] != 3){
			$param[$k]['status_name'] = "<span class='span-primary'>已支付</span>";
		}elseif($v['status'] == 1 && $v['source'] == 3){
			$param[$k]['status_name'] = "<span class='span-danger'>已退款</span>";
		}elseif($v['status'] == 2){
			$param[$k]['status_name'] = "<span class='span-info'>已逾期</span>";
		}elseif($v['status'] == 3){
			$param[$k]['status_name'] = "<span class='span-warning'>已拒绝</span>";
		}elseif($v['status'] == 4){
			$param[$k]['status_name'] = "<span class='span-success'>已同意</span>";
		}elseif($v['status'] == 5){
			$param[$k]['status_name'] = "<span class='span-gray'>已取消</span>";
		}elseif($v['status'] == 6){
			$param[$k]['status_name'] = "<span class='span-gray'>坏账</span>";
		}
		switch ($v['source']) {
			case '0':$param[$k]['source_name'] = '学费';break;
			case '1':$param[$k]['source_name'] = '报销';break;
			case '2':$param[$k]['source_name'] = '罚款';break;
			case '3':$param[$k]['source_name'] = '<span class="span-danger">退款<span>';break;
			case '4':$param[$k]['source_name'] = '其他';break;
			default:$param[$k]['source_name'] = '学费';break;
		}
		$param[$k]['agent_name'] = DB::name('user')->where('id',$v['agent'])->value('real_name');
		// 时间
		$param[$k]['receivables_time'] = date("Y-m-d",$v['receivables_time']);
		if(date("m",$v['finish_time']) == date("m",time())){
			$param[$k]['finish_time'] = date("Y-",$v['finish_time'])
									  . '<span class="span-danger span-strong">'
									  . date("m",$v['finish_time']) .'</span>'
									  . date("-d",$v['finish_time']);
		}else{
			$param[$k]['finish_time'] = date("Y-m-d",$v['finish_time']);
		}

		//姓名 学校专业、部门
		if($v['s_role'] == 1){
			$param[$k]['name'] = DB::name('user')->where('id',$v['s_id'])->value('real_name');
			$role_id = DB::name('user')->where('id',$v['s_id'])->value('role_id');
			$depart_id = DB::name('role')->where('id',$role_id)->value('department_id');
			$depart = DB::name('department')->where('id',$depart_id)->value('name');
			$param[$k]['from'] = $depart;
		}else{
			$st = DB::name('student')->where('id',$v['s_id'])->find();
			if(empty($st)){
				$order = DB::name('order')->where('order_sn',$v['order_sn'])->find();
				$st['name'] = $order['stu_name'];
				$st['school'] = $order['school'];
				$st['major'] = $order['major'];
			}
			$param[$k]['name'] = $st['name'];
			$param[$k]['from'] = $st['school'] . "-" . $st['major'];
		}
		if($v['total_amount'] < 0){
			$param[$k]['total_amount_name'] = '<span class="span-danger">'.$v['total_amount'].'</span>';
		}else{
			$param[$k]['total_amount_name'] = $v['total_amount'];
		}
		// 操作按钮
		// status:0.未支付,1已支付/退款,2已逾期,3.已拒绝, 4.同意,5已取消
		// source:0.学费 1.报销 2.罚款 3.退款 4.其他
		switch ($v['status']) {
			case '0':
				if($v['source'] != 3){
					$param[$k]['operate'] = '<a class="btn btn-sm btn-primary" href="javascript:receivables('.$v["id"].');">收款</a>';
				}else{
					$param[$k]['operate'] = '<span class="span-warning">等待授权</span>';
					$param[$k]['auth'] = '<a class="btn btn-sm btn-success" href="javascript:authRefund('.$v["id"].');">授权</a>';
				}break;
			case '4':
				if($v['source'] == 3){
					$param[$k]['operate'] = '<a class="btn btn-sm btn-danger" href="javascript:receivables('.$v["id"].');">退款</a>';
					$param[$k]['auth'] = DB::name('user')->where('id',$v['auth'])->value('real_name');
				}else{
					$param[$k]['operate'] = '';
				}break;
			case'1':
				$param[$k]['operate'] = '';
				$param[$k]['auth'] = DB::name('user')->where('id',$v['auth'])->value('real_name');
				break;
			case'2':$param[$k]['operate'] = '';break;
			case'3':
				$param[$k]['operate'] = '';
				$param[$k]['auth'] = DB::name('user')->where('id',$v['auth'])->value('real_name');
				break;
			case'5':
				$param[$k]['operate'] = '';
				$param[$k]['auth'] = DB::name('user')->where('id',$v['auth'])->value('real_name');
				break;
			default:$param[$k]['operate'] = '';break;
		}
		if($v['source'] == 0 || $v['source'] == 4){
			$param[$k]['print'] = ' <a class="btn btn-sm btn-success" href="javascript:AccPrint('.$v["id"].');"><i class="fa fa-print"></i></a>';
		}else{
			$param[$k]['print'] = "";
		}

	}
	return $param;
}

/**
 * [伪删除教务流水]
 */
public function delAccount(){
	$param = input('post.');
	$idArr = explode(",",$param['ids']);
	$FincModel = new FinanceModel();
	return $FincModel->delAccount($idArr);
}

/**
 * [财务收款]
 */
public function receivables(){
	$param = input('post.');
	$acc_id = $param['id'];
	$accInfo = DB::name('account')->where('id',$acc_id)->find();
	$source = $accInfo['source'];
	switch ($source) {
		// case'1':return $this->receivables_1($accInfo);break;// 报销
		// case'2':return $this->receivables_2($accInfo);break;// 罚款
		case'3':return $this->receivables_3($accInfo);break;// 退款
		case'0':return $this->receivables_0($accInfo);break;// 学费
		default:return $this->receivables_4($accInfo);break;// 其他
	}
}
/**
 * [学费收款]
 * 1.该订单流水状态变成已收款
 * 2.(如果未支付订单数 == 分期数)读取客户信息写入学员
 * 3.(如果已支付订单数+1 == 分期数)更改订单状态为已完成
 * 4.修改order agent 字段为session（'id'）
 * 5.修改收款时间receivables_time 为 time()
 */
public function receivables_0($accInfo){
	$FincModel = new FinanceModel();
	$MbInfo = DB::name('member')->where('id',$accInfo['m_id'])->find();
	$OrderInfo = DB::name('order')->where('order_sn',$accInfo['order_sn'])->find();
	// 是否新建学员
	$count = $FincModel->getInfoByWhere([
		'order_sn' => $accInfo['order_sn'],
		'status' => 0,
		'source' => 0,
		'delete_status' => 0
	]);
	$payment = DB::name('product_attr')->where('id',$OrderInfo['payment_method'])->value('values');
	$count == $payment ? $is_save = true : $is_save = false;
	// 订单是否已经完成
	$count_1 = $FincModel->getInfoByWhere([
		'order_sn' => $accInfo['order_sn'],
		'status' => 1
	]);
	($count_1 + 1 == $payment) ? $is_over = true : $is_over = false;
	$StData = [
		'name' => $MbInfo['name'],
		'm_id' => $MbInfo['id'],
		'phone' => $MbInfo['phone'],
		'consultant' => $MbInfo['first_relation'],
		'school' => $OrderInfo['school'],
		'school_id' => $OrderInfo['school_id'],
		'major' => $OrderInfo['major'],
		'major_id' => $OrderInfo['major_id'],
		'grade' => $OrderInfo['grade'],
		'school_roll' => 0,
		'school_date' => time(),
	];
	DB::startTrans();
	try{
		$FincModel->setAccStatus($accInfo['id'],1);
		if($is_save){
			$st_id = DB::name('student')->insertGetId($StData);
			DB::name('account')->where('order_sn',$accInfo['order_sn'])->update(['s_id'=>$st_id]);
		}
		if($is_over){
			DB::name('order')->where('order_sn',$accInfo['order_sn'])->update(['status'=>2]);
		}
		DB::commit();
		return ['code'=>1,'msg'=>'收款成功'];
	}catch(\Exception $e){
		DB::rollback();
		return ['code'=>0,'msg'=>'收款失败'.$e->getMessage()];
	}
}
/**
 * [报销单收款]
 */
// public function receivables_1($accInfo){
// 	print_r($accInfo);
// }
/**
 * [罚款单收款]
 */
// public function receivables_2($accInfo){
// 	print_r($accInfo);
// }

/**
 * [退款单收款]
 * 1.更新order.status = 3;order.update_time = time();
 * 2.更新同订单号的流水abnormal = 1;
 * 3.更新同订单号的未支付的且来源为学费的流水的status = 5;update_time = time();agent = session('id');
 * 4.更新account.status = 1;update_time = time();agent = session('id'),;
 */
public function receivables_3($accInfo){
	DB::startTrans();
	try{
		DB::name('order')->where('order_sn',$accInfo['order_sn'])->update([
			'status' => 3,
			'update_time' => time()
		]);
		DB::name('account')->where('order_sn',$accInfo['order_sn'])->update([
			'abnormal' =>1
		]);
		DB::name('account')->where(['order_sn'=>$accInfo['order_sn'],'source'=>0,'status'=>0])->update([
			'status' => 5,
			'update_time' => time(),
			'agent' => session('id')
		]);
		DB::name('account')->where('id',$accInfo['id'])->update([
			'status' => 1,
			'update_time' => time(),
			'agent' => session('id'),
			'receivables_time' => time()
		]);
		DB::commit();
		return ['code'=>1,'msg'=>'退款成功'];
	}catch(\Exception $e){
		DB::rollback();
		return ['code'=>0,'msg'=>'退款失败:'.$e->getMessage()];
	}
}
/**
 * [其他单收款]
 */
public function receivables_4($accInfo){
	$FincModel = new FinanceModel();
	DB::startTrans();
	try{
		$FincModel->setAccStatus($accInfo['id'],1);
		DB::commit();
		return ['code'=>1,'msg'=>'收款成功'];
	}catch(\Exception $e){
		DB::rollback();
		return ['code'=>0,'msg'=>'收款失败'.$e->getMessage()];
	}
}

/**
 * [添加报销单]
 */
public function addExpense(){
	if($this->request->isPost()){
		$param = input('post.');
		$FincModel = new FinanceModel();
		$result = $this->validate($param,'AccountValidate');
		if($result !== true){
			return ['code'=>0,'msg'=>'录入失败:'.$result];
		}
		$data = [
			's_id' => $param['s_id'],
			's_role' => 1,
			'total_amount' => ($param['total_amount'] * -1),
			'remarks' => $param['remarks'],
			'status' => 1,
			'c_time' => time(),
			'finish_time' => time(),
			'source' => 1,
			'create_uid' => session('id'),
			'agent' => session('id')
		];
		return $FincModel->addExpense($data);
	}
	return $this->fetch();
}

/**
 * [添加罚款单]
 */
public function addTicket(){
	if($this->request->isPost()){
		$param = input('post.');
		$FincModel = new FinanceModel();
		$result = $this->validate($param,'AccountValidate');
		if($result !== true){
			return ['code'=>0,'msg'=>'录入失败:'.$result];
		}
		$data = [
			's_id' => $param['s_id'],
			's_role' =>  $param['s_role'],
			'total_amount' => $param['total_amount'],
			'remarks' => $param['remarks'],
			'status' => 1,
			'c_time' => time(),
			'finish_time' => time(),
			'source' => 2,
			'create_uid' => session('id'),
			'agent' => session('id')
		];
		return $FincModel->addExpense($data);
	}
	return $this->fetch();
}

/**
 * [同意/拒绝退款]
 */
public function authRefund(){
	$param = input('post.');
	$param['agree'] == 1 ? $state = 4 : $state = 3 ;
	$id = $param['acc_id'];
	$orderSn = DB::name('account')->where('id',$id)->value('order_sn');
	$orderInfo = DB::name('order')->where('order_sn',$orderSn)->find();
	$orderStatus = ($orderInfo['status'] -30);
	if($state == 3){
		$result = DB::name('order')->where('order_sn',$orderSn)->update(['status' => $orderStatus,'update_time'=>time()]);
		if($result === false){
			return ['code'=>0,'msg'=>'退款授权失败'];
		}
	}
	$FincModel = new FinanceModel();
	return $FincModel->authAccount($id,$state);
}

	/**
	 * [财务统计]
	 */
	public function statistics(){
		if($this->request->isPost()){
			$FincModel = new FinanceModel();
			$param = input('post.');
			//确定时间段和步长
			if(!empty($param['time_slot'])){
				$time_slot_arr = explode(" - ",$param['time_slot']);
				$start_time = strtotime($time_slot_arr[0])." 00:00:00";
				$end_time = strtotime($time_slot_arr[1])." 23:59:59";
			}else{
				$start_time = strtotime('-1 month');
				$end_time = time();
			}
			if(empty($param['time_step'])){
				$time_step = 1 * 24 *3600;//时间步长默认为1天
			}else{
				if(!preg_match("/^\d*$/",$param['time_step']) || $param['time_step']<=0){
					return ['code'=>0,'msg'=>'时间步长输入有误'];
				}
				$time_step = $param['time_step'] * 24 * 3600;
			}
			$pointNum = ceil(($end_time - $start_time) / $time_step);
			$Xdata = [];
			$redData = [];
			$bluData = [];
			for($i=0;$i<=$pointNum;$i++){
				$a = $start_time + $i * $time_step;//第i个时间
				array_push($Xdata,date("Y-m-d",($a)));
				if($i == 0){
					$redData[$i] = DB::name("account")
								 ->where(['status'=>1,'delete_status'=>0,'total_amount'=>['<',0]])
								 ->whereTime('receivables_time','between',[$start_time - $i * $time_step,$a])
								 ->sum('total_amount');
					$redData[$i] *= -1;
					$bluData[$i] = DB::name("account")
							 	 ->where(['status'=>1,'delete_status'=>0,'total_amount'=>['>=',0]])
							 	 ->whereTime('receivables_time','between',[$start_time - $i * $time_step,$a])
							 	 ->sum('total_amount');
				}else{
					$redData[$i] = DB::name("account")
								 ->where(['status'=>1,'delete_status'=>0,'total_amount'=>['<',0]])
								 ->whereTime('receivables_time','between',[strtotime($Xdata[$i-1]),$a])
								 ->sum('total_amount');
					$redData[$i] *= -1;
					$bluData[$i] = DB::name("account")
 								 ->where(['status'=>1,'delete_status'=>0,'total_amount'=>['>=',0]])
 								 ->whereTime('receivables_time','between',[strtotime($Xdata[$i-1]),$a])
 								 ->sum('total_amount');
				}
			}
			$pieData[0]['name'] = "学费";
			$pieData[0]['value'] = $this->ForPieData($start_time,$end_time,0);
			$pieData[1]['name'] = "报销";
			$pieData[1]['value'] = $this->ForPieData($start_time,$end_time,1);
			$pieData[2]['name'] = "罚款";
			$pieData[2]['value'] = $this->ForPieData($start_time,$end_time,2);
			$pieData[3]['name'] = "退款";
			$pieData[3]['value'] = $this->ForPieData($start_time,$end_time,3);
			$pieData[4]['name'] = "其他";
			$pieData[4]['value'] = $this->ForPieData($start_time,$end_time,4);

			return ['code'=>1,'msg'=>'图表加载成功','Xdata' => $Xdata,'redData'=>$redData,'bluData'=>$bluData,'pieData'=>$pieData];
		}
		return $this->fetch();
	}

	public function ForPieData($start_time,$end_time,$source){
		$money =  DB::name("account")
				 ->where(['status'=>1,'delete_status'=>0,'source'=>$source])
				 ->whereTime('receivables_time','between',[$start_time,$end_time])
				 ->sum('total_amount');
		if($money < 0){
			$money *= -1;
		}
		return $money;
	}
	/**
	 * [财务报表]
	 */
	 public function accReportList (){
 		$FincModel = new FinanceModel();
		/*
		// 离散收款时间
        $start_time = strtotime("2018-05-01");
        $end_time = strtotime("2018-05-10");

        $num = DB::name('account')->where('status',1)->count();
        if($num == 0){
            return ['code'=>0,'msg'=>'表中没有数据'];
        }
        $step = abs($end_time - $start_time) / $num;//步长

        DB::startTrans();
        try {
            $k = 1;// id起始
            for($i = $start_time;$i <= $end_time; $i += $step){
                DB::name('account')->where('id',$k)->update(['receivables_time'=>$i]);
                $k ++ ;
            }
            Db::commit();
            return ['code'=>1,'msg'=>'成功'];
        } catch (Exception $e) {
            Db::rollback();
            return ['code'=>0,'msg'=>'失败'.$e];
        }
		*/
 		if(request()->isAjax()){
 			$param = input('param.');
 			$where = ['delete_status' => 0];
 			$sortName = input('sortName');
 			$sortOrder = input('sortOrder');
			if(empty($param['seaTime'])){
				$param['seaTime'] = date("Y-m-d")." - ".date("Y-m-d");
			}
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$orderBy = $sortName." ".$sortOrder;
			$this->WhereSn($param['seaSn'],$FincModel);
			$this->WhereName($param['seaName'],$FincModel);
			$this->WhereSource($param['seaSource'],$FincModel);
			$this->WhereStatus($param['seaStatus'],$FincModel);
			$this->WhereTimeReport($param['seaTime'],$FincModel);
			$return['rows'] = $FincModel->getInfoByWhere($where,true,$offset,$limit,$orderBy);
			$this->WhereSn($param['seaSn'],$FincModel);
			$this->WhereName($param['seaName'],$FincModel);
			$this->WhereSource($param['seaSource'],$FincModel);
			$this->WhereStatus($param['seaStatus'],$FincModel);
			$this->WhereTimeReport($param['seaTime'],$FincModel);
			$return['total'] = $FincModel->getInfoByWhere($where);
			$return['rows'] = $this->translateFince($return['rows']);
			$return['sum'] = 0;
			foreach($return['rows'] as $k => $v){
				$return['sum'] += $v['total_amount'];
			}
			return $return;
 		}
 		return $this->fetch();
 	}

	/**
	 * [打印收据]
	 */
	public function AccPrint(){
		$acc_id = input('get.acc_id');
		$FincModel = new FinanceModel;
		$accInfo = DB::name('account')->where('id',$acc_id)->find();
		$orderInfo = DB:: name('order')->where('order_sn',$accInfo['order_sn'])->find();
		$stInfo = DB:: name('student')->where('id',$accInfo['s_id'])->find();
		if($stInfo['sex'] == 0){
			$sex = "保密";
		}elseif($stInfo['sex'] == 1){
			$sex = "男";
		}else{
			$sex = "女";
		}
		$agent = DB::name('user')->where('id',$accInfo['agent'])->value('real_name');
		$writer = DB::name('user')->where('id',session('id'))->value('real_name');
		$first_relation = DB::name('user')->where('id',$orderInfo['first_relation'])->value('real_name');
		$role_id = DB::name('user')->where('id',$orderInfo['first_relation'])->value('role_id');
		$depart_id = DB::name('role')->where('id',$role_id)->value('department_id');
		$depart = DB::name('department')->where('id',$depart_id)->value('name');
		$grade = DB::name('product_attr')->where('id',$orderInfo['grade'])->value('name');
		$acquisition_mode = DB::name('product_attr')->where('id',$orderInfo['acquisition_mode'])->value('name');
		$this->assign([
			'accInfo' => $accInfo,
			'orderInfo' => $orderInfo,
			'stInfo' => $stInfo,
			'sex' => $sex,
			'agent' => $agent,
			'writer' => $writer,
			'first_relation' => $first_relation,
			'depart' => $depart,
			'grade' => $grade,
			'acquisition_mode' => $acquisition_mode,
		]);
		return $this->fetch();
	}

	/**
	 * [待处理流水]
	 */
	public function pendbill(){
		$FincModel = new FinanceModel();
		if(request()->isAjax()){
			$param = input('param.');
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$where = ['delete_status'=>0,'source'=>0];
			$FincModel->where(function($query)use($param){
				$query->whereOr('status',2);
				$query->whereOr('status',5);
				$query->whereOr('status',6);
			});
			$sortName = input('sortName');
			$sortOrder = input('sortOrder');
			$orderBy = $sortName." ".$sortOrder;
			$this->WhereSn($param['seaSn'],$FincModel);
			$this->WhereName($param['seaName'],$FincModel);
			$this->WhereStatus($param['seaStatus'],$FincModel);
			$this->WhereTime($param['seaTime'],$FincModel);
			$return['rows'] = $FincModel->getInfoByWhere($where,true,$offset,$limit,$orderBy);
			$FincModel->where(function($query)use($param){
				$query->whereOr('status',2);
				$query->whereOr('status',5);
				$query->whereOr('status',6);
			});
			$this->WhereSn($param['seaSn'],$FincModel);
			$this->WhereName($param['seaName'],$FincModel);
			$this->WhereStatus($param['seaStatus'],$FincModel);
			$this->WhereTime($param['seaTime'],$FincModel);
			$return['total'] = $FincModel->getInfoByWhere($where);
			$return['rows'] = $this->translateFince($return['rows']);
			foreach($return['rows'] as $k => $v){
				$return['rows'][$k]['operation'] = '';
				if(authCheck('finance/receivables') && $v['status'] != 5){
					$return['rows'][$k]['operation'] .= '<a class="btn btn-sm btn-primary" href="javascript:receivables('.$v['id'].');">收款</a>';
				}
				if(authCheck('finance/acccancel') && $v['status'] != 5){
					$return['rows'][$k]['operation'] .= ' <a class="btn btn-sm btn-warning" href="javascript:accCancel('.$v['id'].');">取消</a>';
				}
			}
			return $return;
		}
		return $this->fetch();
	}
	/**
	 * [取消该订单]
	 */
	public function accCancel(){
		$id = input('post.id');
		DB::startTrans();
		try{
			$orderSn = DB::name('account')->where('id',$id)->value('order_sn');
			DB::name('account')->where('order_sn',$orderSn)->update(['status'=>5,'agent'=>session('id')]);
			DB::name('order')->where('order_sn',$orderSn)->update(['status'=>0]);
			DB::commit();
			return ['code'=>1,'msg'=>'操作成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'操作失败：'.$e->getMessage()];
		}
	}
}
